package com.glorystone.ins.controller;

import com.glorystone.ins.beanUtils.BeanUtils;
import com.glorystone.ins.beanUtils.ExcelUtil;
import com.glorystone.ins.common.common.DataTable;
import com.glorystone.ins.common.common.PageVo;
import com.glorystone.ins.common.util.DateEnum;
import com.glorystone.ins.common.util.DateUtils;
import com.glorystone.ins.domain.*;
import com.glorystone.ins.interceptor.PageList;
import com.glorystone.ins.service.ChannelService;
import com.glorystone.ins.service.IDictionaryService;
import com.glorystone.ins.service.InsurerService;
import com.glorystone.ins.service.OrderEndpayingService;
import com.glorystone.ins.vo.EndpayingCVo;
import com.glorystone.ins.vo.EndpayingIVo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author:haoguodong
 * @Date:Created in 16:19 2018/3/26
 * @since: JDK 1.7
 * @projectName:IntelliJ IDEA
 * @Description:类功能描述
 */
@Controller
@RequestMapping("/repay")
public class OrderRepayController extends BaseController {

    @Autowired
    private OrderEndpayingService orderEndpayingService;


    @Autowired
    private InsurerService insurerService;

    @Autowired
    private ChannelService channelService;

    @Autowired
    private IDictionaryService iDictionaryService;

    /**
     * 已退保页面
     */
    @RequestMapping(value = "/toList", method = RequestMethod.GET)
    public ModelAndView toRepayList(ModelAndView mv) {
        List<Insurer> list = insurerService.selectAllInsurer();
        List<Channel> channels = channelService.findAll();
        List<Dictionary> dlist = iDictionaryService.getDictionaryListByType("PAY_THEME");
        mv.addObject("insurerList",list);
        mv.addObject("channels",channels);
        mv.addObject("dictionary",dlist);
        mv.setViewName("order/removeOrder");
        return mv;
    }

    /**
     *保险公司和渠道列表展示
     */
    @RequestMapping(value="/queryInsurerData",method = RequestMethod.GET)
    @ResponseBody
    public DataTable<Endpaying> queryTableData(HttpServletRequest request){
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        PageVo vo =  parametToPageVoData(request,Endpaying.class,user);
        PageList<Endpaying> list = orderEndpayingService.queryRepayList(vo);
        DataTable data = resultToDataTable(list);
        return data;
    }

    /**
     * 导出保险公司数据
     */
    @RequestMapping("/downloadis")
    public void exportRepayiInfo(HttpServletRequest request, HttpServletResponse response) {
        String capitalStatus = request.getParameter("capitalStatus");
        String insyrerId = request.getParameter("insyrerId");
        String ordNum = request.getParameter("ordNum");
        String channelId = request.getParameter("channelId");
        String dateIssuanceStart = request.getParameter("dateIssuanceStart");
        String dateIssuanceEnd = request.getParameter("dateIssuanceEnd");
        String surrenderDateStart = request.getParameter("surrenderDateStart");
        String surrenderDateEnd = request.getParameter("surrenderDateEnd");
        Map<String,String> map = Maps.newHashMap();
        map.put("capitalStatus",capitalStatus);
        map.put("insyrerId",insyrerId);
        map.put("ordNum",ordNum);
        map.put("channelId",channelId);
        map.put("dateIssuanceStart",dateIssuanceStart);
        map.put("dateIssuanceEnd",dateIssuanceEnd);
        map.put("surrenderDateStart",surrenderDateStart);
        map.put("surrenderDateEnd",surrenderDateEnd);
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Long userId =user.getTid();
        int level = user.getUserLevel();
        if(3==level){
            map.put("userId",""+userId);
        }
        List<Dictionary> dlist = iDictionaryService.getDictionaryListByType("PAY_THEME");
        List<Endpaying> list = orderEndpayingService.getEndpayList(map);
        List<EndpayingIVo> rList = Lists.newArrayList();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        for(Endpaying ep:list){
            EndpayingIVo rv = new EndpayingIVo();
            rv.setOrdNum(ep.getOrdNum());
            for(Dictionary d:dlist){
                if(d.getRiskKey().equals(""+ep.getPaySubject())){
                    rv.setPaySubject(d.getRiskValue());
                }
            }
            rv.setInsyrerName(ep.getInsyrerName());
            if(1==ep.getChannelType()){
                rv.setChannelName(ep.getChannelPName());
            }else{
                rv.setChannelName(ep.getChannelCName());
            }
            rv.setChannelPhone(ep.getChannelPhone());
            if(1==ep.getTypeInsurance()){
                rv.setTypeInsurance("商业险");
            }else{
                rv.setTypeInsurance("交强险");
            }
            rv.setInsurant(ep.getInsurant());
            rv.setOrgIdCode(ep.getOrgIdCode());
          /*  rv.setApplicant(ep.getApplicant());*/
            rv.setPlateNum(ep.getPlateNum());
            rv.setCarOwner(ep.getCarOwner());
            rv.setMercialPremium(""+ep.getMercialPremium());
            rv.setPulsoryPremium(""+ep.getPulsoryPremium());
            rv.setVechcleVesselTax(""+ep.getVechcleVesselTax());
            rv.setAllPremium(""+ep.getAllPremium());
            rv.setCreateDate(ep.getCreateDate());
            rv.setDatePolicy(ep.getDatePolicy());
            rv.setSalemanName(""+ep.getSalemanName());
            rv.setSurrenderDate(ep.getSurrenderDate());
            rv.setPayInsurerAmt(""+ep.getPayInsurerAmt());
            rv.setCheckDate(ep.getCheckDate());
            rList.add(rv);
        }
        List<String> titles = new BeanUtils().operateBeans(new EndpayingIVo(),0);
        String fileName = "保险公司已退保数据导出 " + DateUtils.dateToStr(new Date(), DateEnum.DATE_BANK_SEQ);
        XSSFWorkbook workbook = new ExcelUtil().getXlsxWorkbook(titles,rList,fileName,0);
        response.reset();
        try {
            //导出支持中文名，兼容IE、火狐
            if (request.getHeader("user-agent").indexOf("MSIE") != -1) {
                fileName = java.net.URLEncoder.encode(fileName, "utf-8") + ".xlsx";
            } else {
                fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1") + ".xlsx";
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出渠道数据
     */
    @RequestMapping("/downloadc")
    public void exportRepaycInfo(HttpServletRequest request, HttpServletResponse response) {
        String capitalStatus = request.getParameter("capitalStatus");
        String insyrerId = request.getParameter("insyrerId");
        String ordNum = request.getParameter("ordNum");
        String channelId = request.getParameter("channelId");
        String dateIssuanceStart = request.getParameter("dateIssuanceStart");
        String dateIssuanceEnd = request.getParameter("dateIssuanceEnd");
        String surrenderDateStart = request.getParameter("surrenderDateStart");
        String surrenderDateEnd = request.getParameter("surrenderDateEnd");
        Map<String,String> map =Maps.newHashMap();
        map.put("capitalStatus",capitalStatus);
        map.put("insyrerId",insyrerId);
        map.put("ordNum",ordNum);
        map.put("channelId",channelId);
        map.put("dateIssuanceStart",dateIssuanceStart);
        map.put("dateIssuanceEnd",dateIssuanceEnd);
        map.put("surrenderDateStart",surrenderDateStart);
        map.put("surrenderDateEnd",surrenderDateEnd);
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Long userId =user.getTid();
        int level = user.getUserLevel();
        if(3==level){
            map.put("userId",""+userId);
        }
        List<Dictionary> dlist = iDictionaryService.getDictionaryListByType("PAY_THEME");
        List<Endpaying> list = orderEndpayingService.getEndpayList(map);
        List<EndpayingCVo> rList = Lists.newArrayList();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        for(Endpaying rp:list){
            EndpayingCVo rv = new EndpayingCVo();
            rv.setOrdNum(rp.getOrdNum());
            for(Dictionary d:dlist){
                if(d.getRiskKey().equals(""+rp.getPaySubject())){
                    rv.setPaySubject(d.getRiskValue());
                }
            }
            rv.setInsyrerName(rp.getInsyrerName());
            if(1==rp.getChannelType()){
                rv.setChannelName(rp.getChannelPName());
            }else{
                rv.setChannelName(rp.getChannelCName());
            }
            rv.setChannelPhone(rp.getChannelPhone());
            if(1==rp.getTypeInsurance()){
                rv.setTypeInsurance("商业险");
            }else{
                rv.setTypeInsurance("交强险");
            }
            rv.setInsurant(rp.getInsurant());
            rv.setOrgIdCode(rp.getOrgIdCode());
           /* rv.setApplicant(rp.getApplicant());*/
            rv.setPlateNum(rp.getPlateNum());
            rv.setMercialPremium(""+rp.getMercialPremium());
            rv.setPulsoryPremium(""+rp.getPulsoryPremium());
            rv.setVechcleVesselTax(""+rp.getVechcleVesselTax());
            rv.setAllPremium(""+rp.getAllPremium());

            rv.setDateIssuance(rp.getDateIssuance());
            rv.setDatePolicy(rp.getDatePolicy());
            rv.setChannelRebate(""+rp.getChannelRebate());
            rv.setInsureMustRebateAmt(""+rp.getInsureMustRebateAmt());
            rv.setInsureMustPremium(""+rp.getInsureMustPremium());
            rv.setInsureRealPremium(""+rp.getInsureRealPremium());
            rv.setInsyrerMaturityDate(rp.getInsyrerMaturityDate());
            rv.setSurrenderDate(""+rp.getSurrenderDate());
            rv.setMustRebateAmt(""+rp.getMustRebateAmt());
            rv.setMustPremium(""+rp.getMustPremium());
            BigDecimal reb=rp.getMustRebateAmt();
            BigDecimal pre=rp.getMustPremium();
            if(reb == null){
                reb = new BigDecimal(0);
            }
            if(pre == null){
                pre = new BigDecimal(0);
            }
            reb=reb.add(pre);
            rv.setRealRebateAmt(""+reb);
            rv.setInsureEndDate(""+rp.getInsureEndDate());
            rv.setSalemanName(""+rp.getSalemanName());
            rList.add(rv);
        }
        List<String> cTitles = new BeanUtils().operateBeans(new EndpayingCVo(),0);
        String fileName = "渠道已退保数据导出 " + DateUtils.dateToStr(new Date(), DateEnum.DATE_BANK_SEQ);
        XSSFWorkbook workbook = new ExcelUtil().getXlsxWorkbook(cTitles,rList,fileName,0);
        response.reset();
        try {
            //导出支持中文名，兼容IE、火狐
            if (request.getHeader("user-agent").indexOf("MSIE") != -1) {
                fileName = java.net.URLEncoder.encode(fileName, "utf-8") + ".xlsx";
            } else {
                fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1") + ".xlsx";
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
